package com.lw.spring.javademo;

import java.io.*;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
    private String message;

    public void init() {
        message = "Hello JAVAWEB";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 获取所有的 Cookies
        Cookie[] cookies = request.getCookies();

        boolean loginSuccess = false;

        // 检查 Cookie 中是否包含名为 "login" 且值为 "success" 的 Cookie
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("login".equals(cookie.getName()) && "success".equals(cookie.getValue())) {
                    loginSuccess = true;
                    break; // 找到匹配的 Cookie 后就可以退出循环
                }
            }
        }
        // 如果没有找到符合要求的 Cookie，则跳转到登录页面
        if (!loginSuccess) {
            response.sendRedirect("html/login.html"); // 或者其他登录页面
            return; // 不继续执行后面的代码
        }
        // 如果 Cookie 中有 login=success
        response.setContentType("text/html");

        // 输出 HTML 页面
        /*PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>Welcome! You are logged in.</h1>");
        out.println("</body></html>");*/
        request.setAttribute("message", message);/////////
        request.getRequestDispatcher("/WEB-INF/jsp/message.jsp").forward(request, response);
    }

    public void destroy() {
    }
}